import Message from '@/components/message'
import useStore from '@/store'
import axios, { AxiosError } from 'axios'

const request = axios.create({
	baseURL: 'http://pcapi-xiaotuxian-front.itheima.net/',
	// baseURL: 'https://apipc-xiaotuxian-front.itheima.net/',
	timeout: 5000,
})
// 请求拦截
request.interceptors.request.use(
	(config) => {
		const { user } = useStore()
		if (user.profile.token) {
			config.headers!.Authorization = `Bearer ${user.profile.token}`
		}
		// if (user.profile.token && config.headers) {
		// 	config.headers.Authorization = `Bearer ${user.profile.token}`
		// }
		return config
	},
	(error) => {
		return Promise.reject(error)
	}
)
// 响应拦截
request.interceptors.response.use(
	(res) => {
		return res
	},
	(error: AxiosError<any>) => {
		// 网络太慢，超过请求限时5000ms，error都没有
		if (!error.response) {
			Message.error('网络异常，请稍后再试')
		} else {
			Message.error(error.response.data.message)
		}
		return Promise.reject(error)
	}
)
export default request
